<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属站点" prop="mixingStationNumber">
          <el-select v-model="queryParams.mixingStationNumber" placeholder="请选择所属站点" clearable class="!w-220px">
            <el-option v-for="(item, index) in mixingStationOptions" :key="index" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>

        <el-form-item label="车牌号码" prop="carNumber">
          <el-input v-model="queryParams.carNumber" placeholder="请输入车牌号码" clearable />
        </el-form-item>

        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="queryParams.deviceId" placeholder="请输入设备ID" clearable />
        </el-form-item>

        <el-form-item label="搅拌车号" prop="mixingCarCode">
          <el-input v-model="queryParams.mixingCarCode" placeholder="请输入搅拌车号" clearable />
        </el-form-item>

        <el-form-item label="车辆状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择车辆状态" clearable class="!w-220px">
            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间" prop="timeType">
          <el-select v-model="queryParams.timeType" class="!w-220px">
            <el-option v-for="(item, index) in dateTypeOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item prop="startTime">
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <div></div>
          <!-- <el-button type="success" @click="handleOpenDialog()">
            <template #icon><ep-Plus /></template>
            新增
          </el-button> -->
          <el-button class="ml-3" @click="handleExport">
            <template #icon><ep-Download /></template>
            导出
          </el-button>
        </div>
      </template>

      <el-table v-auto-h v-loading="loading" :data="tableData" border>
        <el-table-column label="车牌号码" width="120" align="center" prop="carNumber" />
        <el-table-column label="设备ID" width="120" align="center" prop="deviceId" />
        <el-table-column label="所属站点" min-width="200" align="center" prop="mixingStationName" />
        <el-table-column label="搅拌车号" min-width="120" align="center" prop="mixingCarCode" />
        <el-table-column label="核载重量" width="100" align="center" prop="weightLimit" />
        <el-table-column label="车辆状态" width="100" align="center" prop="status">
          <template #default="{ row }">
            <el-tag :type="row.status === statusOptions[0].value ? 'success' : 'info'">
              {{ statusOptions.find(item => item.value === row.status)?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="失效时间" width="180" align="center" prop="invalidTime" />
        <el-table-column label="更新人" width="110" align="center" prop="updateBy" />
        <el-table-column label="更新时间" width="180" align="center" prop="updateTime" />
        <el-table-column label="创建人" width="110" align="center" prop="createBy" />
        <el-table-column label="创建时间" width="180" align="center" prop="createTime" />

        <!-- <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleOpenDialog(row)">
              <template #icon><ep-Edit /></template>
              编辑
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-model:page="current" v-model:pagesize="pageSize" :total="total" />
    </el-card>

    <!-- 添加/编辑表单弹框 -->
    <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-body @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="车牌号码" prop="carNumber">
          <el-input v-model="formData.carNumber" placeholder="请输入车牌号码" />
        </el-form-item>

        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="formData.deviceId" placeholder="请输入设备ID" />
        </el-form-item>

        <el-form-item label="所属站点" prop="mixingStationNumber">
          <el-select v-model="formData.mixingStationNumber" placeholder="请选择所属站点">
            <el-option v-for="item in mixingStationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>

        <el-form-item label="搅拌车号" prop="mixingCarCode">
          <el-input v-model="formData.mixingCarCode" placeholder="请输入搅拌车号" />
        </el-form-item>

        <el-form-item label="核载重量" prop="weightLimit">
          <el-input v-model="formData.weightLimit" placeholder="请输入核载重量" />
        </el-form-item>

        <el-form-item label="失效时间" prop="invalidTime">
          <el-date-picker v-model="formData.invalidTime" type="datetime" placeholder="请选择失效时间" />
        </el-form-item>

        <el-form-item label="车辆状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            :active-text="statusOptions[0].label"
            :inactive-text="statusOptions[1].label"
            :active-value="statusOptions[0].value"
            :inactive-value="statusOptions[1].value"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { useRequest, usePagination } from '@/hooks/useRequest'
import type { FormInstance } from 'element-plus'
import { statusOptions, dateTypeOptions } from './options'
import { getMixingStationList, type MixingStationData } from '@/api/customer/customer'
import { getPage, exportPage, addOrUpdate } from '@/api/vehicle/vehicle'
// import type { VehiclePageQuery, Data, Form } from '@/api/vehicle/vehicle'
import type { VehiclePageQuery, Form } from '@/api/vehicle/vehicle'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'

const queryFormRef = ref<FormInstance>()

const queryParams = reactive<VehiclePageQuery>({ nowPage: 1, pageSize: 10, timeType: 1 })

const { data, loading, run, total, current, pageSize } = usePagination(getPage, { defaultParams: [queryParams], manual: true })

const tableData = computed(() => data.value?.result.records || [])

const handleQuery = () => {
  run(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value!.resetFields()
  queryParams.endTime = undefined
  handleQuery()
}

const handleExport = () => {
  exportPage(queryParams)
}

// 获取搅拌站下拉数据
const { data: mixingStationData } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queryParams.mixingStationNumber = defaultMixingStation.number
    }
  },
  onAfter() {
    handleQuery()
  }
})
const mixingStationOptions = computed(() => mixingStationData.value?.result || [])

/** --------------------- 添加编辑部分 -------------------- */
const drawer = reactive({
  title: '',
  visible: false
})

const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive<Form>({ status: 1 })

const rules = reactive({
  carNumber: [{ required: true, message: '请输入车牌号码', trigger: 'blur' }],
  // deviceId: [{ required: true, message: '请输入设备ID', trigger: 'blur' }],
  mixingStationNumber: [{ required: true, message: '请选择所属站点', trigger: 'change' }],
  mixingCarCode: [{ required: true, message: '请输入搅拌车号', trigger: 'blur' }],
  weightLimit: [{ required: true, message: '请输入核载重量', trigger: 'blur' }],
  status: [{ required: true, message: '请选择车辆状态', trigger: 'change' }]
})

// const handleOpenDialog = async (row?: Data) => {
//   drawer.visible = true
//   if (row) {
//     drawer.title = '编辑车辆信息'
//     await nextTick()
//     Object.assign(formData, row)
//   } else {
//     drawer.title = '新增车辆信息'
//   }
// }

const handleCloseDialog = () => {
  drawer.visible = false
  formRef.value.resetFields()
  formData.id = undefined
}

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitLoading.value = true
      addOrUpdate(formData)
        .then(() => {
          ElMessage.success(formData.id ? '修改成功' : '新增成功')
          handleCloseDialog()
          handleQuery()
        })
        .finally(() => (submitLoading.value = false))
    }
  })
}
</script>
<style lang="scss" scoped></style>
